package yy.robot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import yy.robot.domain.Paging;
import yy.robot.domain.Robot;
import yy.robot.service.RobotService;

/**
 * Created by BaiJiFeiLong@gmail.com at 2018/5/3 11:13
 */
@RestController
@RequestMapping("/robots")
public class RobotController {

    private final RobotService robotService;

    @Autowired
    public RobotController(RobotService robotService) {
        this.robotService = robotService;
    }

    @GetMapping
    public Paging<Robot> index(
            @RequestParam(required = false, defaultValue = "0") int page,
            @RequestParam(required = false, defaultValue = "10") int size
    ) {
        Page<Robot> robotPage = robotService.findAll(PageRequest.of(page, size));
        return Paging.fromPage(robotPage);
    }

    @PostMapping
    public Robot create(
            Robot robot
    ) {
        return robotService.create(robot);
    }

    @GetMapping("{id}")
    public Robot show(@PathVariable long id) {
        return robotService.findById(id);
    }

    @PatchMapping("{id}")
    public Robot update(
            @PathVariable long id,
            Robot robot
    ) {
        robot.setId(id);
        return robotService.update(robot);
    }

    @DeleteMapping("{id}")
    public void delete(@PathVariable long id) {
        robotService.destroy(id);
    }
}
